﻿function TalkBack(){
	wave.getState().submitDelta({ TB_Req : "1" });	
}

//this is a getter- gets the cost from the state
function getCost()
{
	if ( wave.getState() )
	{
		return parseFloat( wave.getState().get( "cost", "0" ) );
	}
	else
	{
		return 0;
	}
}

//this is a getter- gets the aggregated cost from the state
function getAggCost()
{
	if ( wave.getState() )
	{
		return parseFloat( wave.getState().get( "agg_cost", "0" ) );
	}
	else
	{
		return 0;
	}
}

//this is a getter- gets the aggregated prize from the state
function getAggPrize()
{
	if ( wave.getState() )
	{
		return parseInt( wave.getState().get( "agg_prize", "0" ) );
	}
	else
	{
		return 0;
	}
}

/* 1 React to a cell click. */
function cellClick( row, col ){
	
	if(IsRightTime(getDateFromState("cellClickLowerLimit"),getDateFromState("cellClickUpperLimit"))){ // added to lock availablity of form
		// Get the current state of play.
		verifyWaveID();
		var game = gameState();
		var name=wave.getViewer().getDisplayName();
		var num=0;
		var cost=new Number();
		var parId=wave.getViewer().getId();
		var new_account=accountState();
		var agreeFlag=0;
		// Make the move.
		if (col<3)   {
			//calculate number of cols (cols= TURIM in hebrew, this is the way toto calculates the cost).
			game[row][col] = !game[row][col];
			var colsArray=getCols(game);
			var numOfCols= colsArray[16];
			var legal=legalFillout(colsArray[18],colsArray[19]);

			//checking legality of the fillout
			if (legal==10){
				if (game[row][col]){
					updateServlet(1,row,col);
					new_account[row][col]=parId;
					agreementClick(row,col,game,1);
				}
				else {
					new_account[row][col]="";
					updateServlet(0,row,col);
					agreementClick(row,col,game,0);
				}
				cost=(numOfCols*2.8).toFixed(2);	
				// Write the state of play back to the Wave.
				wave.getState().submitDelta( { "game"  : wave.util.printJson( game ),
					"moves" : getMoves() + 1,
					"cost" : cost,
					"account":wave.util.printJson(new_account)});
			}
			else {
				game[row][col] = !game[row][col];
				alertFillout(legal);				 
			}
		}
	}// close isRightTime
	else{
	 jAlert('הלו הלו! את הנעשה אין להשיב! אי אפשר לשנות את הטופס אחרי שבת בבוקר', 'פעולה לא חוקית');
	}
} //close function

// 	this function represents the clicks in the personal form of the viewer.
//	it updates the agreement array,the viewer's personal inner form, and (if necessary) the actual form
// when there is no one voting for a square in his inner form, the actual form will turn off.
// this funtion can accept a game element (16x3) and a wanted value (this for efficiant use in cellClick).
// if no game and value were givan (regular agreementClick) it will retrieve the needed values on the fly.
// to disable the use of givan values use (givenGame=false ,givenVal>1) as input.
function agreementClick(row,col,givenGame,givenVal){
	if(givenVal<=1 || IsRightTime(getDateFromState("cellClickLowerLimit"),getDateFromState("cellClickUpperLimit"))){	
		var isEmptyFlag = 1;
		var game = (givenGame==false ? gameState() : givenGame);
		//set the the viewer's profile
		var parId=wave.getViewer().getId();
		var profile=profileState(parId);
		if(col==3){//clear profile mode
			for(k=0 ; k<3 ; k++){
				profile[row][k]=0
			}
		}
		else{//regular agreementClick
			var val=(givenVal>1 ? (profile[row][col]==1?0:1) : givenVal);
			profile[row][col]=val;
		}
		//set the game (the global form) and agreement
		var gameProfile=getGameProfile(row,parId,profile);
		var agreement=agreementState();
		agreement[row]=0;
		for (col=0;col<3;col++){		
			//set the form if needed
			if ((gameProfile[col].length ==0)&&(game[row][col])){
				game[row][col]=false;
			}
			//set the agreement
			if((gameProfile[col].length!=0)&&(!game[row][col])){
				agreement[row]=1;
			}
			else if (game[row][col]){isEmptyFlag=0;}
		}
		if (isEmptyFlag==1){agreement[row]=0;} //no disagreement when nothing is marked
		
		delta = {};
		var hesutationCountHelper = getSomething(parId + "HChelper",0);
		var rowBinRep = Math.pow(2,(row-1)); //row binaric representation
		if (hesutationCountHelper & rowBinRep){
			var hesitationCount = getSomething(parId+"HC",0) + 1;
			delta[parId+"HC"] = hesitationCount;
		}
		else{
			delta[parId+"HChelper"] = (hesutationCountHelper | rowBinRep);
		}
		delta[parId] = wave.util.printJson(profile);
		delta["game"] = wave.util.printJson(game);
		delta["agreement"] = wave.util.printJson(agreement);
		//update agreement
		//alert(agreement);
		wave.getState().submitDelta(delta); 
	}
	else{
		//$.fn.colorbox.close();
     
		jAlert('הלו הלו! את הנעשה אין להשיב! אי אפשר לשנות את הטופס אחרי שבת בבוקר', 'פעולה לא חוקית');
		
	}
}

//this function refreshes the display of the agreement bar
function refreshAgreement(){
	var agreement = agreementState();
	for(i=0;i<16;i++){
		document.getElementById("agree"+i).setAttribute("class",(agreement[i] ? "disagree_button" : "agree_button"));
	}
}

function refreshAgreementDivs(){
	var GP;
	for(l=0;l<16;l++){
		GP = getGameProfile(l,0,0);
		document.getElementById("agreement_div"+l).innerHTML = "<table cellspacing='2' border='0' cellpading='3'>"+CreateSingleGameTable(GP,l)+"</table>";
	}
}

function clearAllProfiles(){
	var par=wave.getParticipants();
	var delta = {};
	//reste the agreement Array
	delta["agreement"] = wave.util.printJson(defaultAgreement());
	//reset the personal profiles
	var newProfile = wave.util.printJson(defaultProfile());
	for (i = 0; i < par.length;i++){
		alert(newProfile);
		delta[par[i].getId()] = newProfile;
	}
	wave.getState().submitDelta(delta);
}

//This function checks whether there is a dispute regarding game # row (that is, there is someone that thinks something that is not reflected in the form ,and the form is not empty for that game) 
function checkAgreement(row,newParId,newProfile,game){
	var agreement=agreementState();
	var gameProfile=getGameProfile(row,newParId,newProfile);
	var isEmptyFlag=1;
	agreement[row]=0;
	for (col=0;col<3;col++){
		if ((gameProfile[col].length!=0)&&(!game[row][col])){
			agreement[row]=1;
		}
		if (game[row][col]){
			isEmptyFlag=0;
		}
	}
	if (isEmptyFlag==1)
		agreement[row]=0;
	wave.getState().submitDelta( { "agreement"  : wave.util.printJson( agreement )});
	return agreement[row];
}

//This function gets: row= a game # and ; newParId= the id of the participant whose profile was just updated; newProfile= the new profiel of newParId (that is not updated in the state yet)
//returns an array of concatenated Id's of participants (divided by #), 
//such that the y cell holds the participants ids that have marked the y column for this game 
//with the exception that the fourth is for neutral participants 
function getGameProfile(row,newParId,newProfile){
	var gameProfile=[new Array(),new Array(),new Array(),new Array()]; 
	var par=wave.getParticipants();
	for (j_new = 0;j_new < par.length;j_new++){
		var flag=0;
		var parId=par[j_new].getId();
		var parPic="<img src=" + par[j_new].getThumbnailUrl() + " style='height:42px;width:42px'>"; 
		var profile=profileState(parId);
		if (parId==newParId)
			profile=newProfile;
		for (col=0;col<3;col++){
			if (profile[row][col]==1){
				flag=1;
				gameProfile[col].push(parPic);
			}
		}
		if (flag==0)
			gameProfile[3].push(parPic);
	}		
	return gameProfile;
}

//this function builds the table you see when looking at the personal form games
function CreateSingleGameTable(gameProfile,gameNum){
	var userProfile = profileState(wave.getViewer().getId());
	var maxCol = FindMaxCol(gameProfile);
	reverseArray(gameProfile, 4);
	
	var HTMLgametable = "<tr><td><div class='solve_dispute' onclick=agreementClick("+gameNum+",3,false,2)><div class='solve_dispute_left'>נייטרלי</div><div class='solve_dispute_right'>&nbsp;</div></td>"+
                    "<td width='44' align='center'><div class="+(userProfile[gameNum][2]?"innerCellOn":"innerCellOff") + " onclick=agreementClick("+gameNum+",2,false,2)>1</div></td>"+
                    "<td width='44' align='center'><div class="+(userProfile[gameNum][1]?"innerCellOn":"innerCellOff") + " onclick=agreementClick("+gameNum+",1,false,2)>X</div></td>"+                    
                    "<td width='44' align='center'><div class="+(userProfile[gameNum][0]?"innerCellOn":"innerCellOff") + " onclick=agreementClick("+gameNum+",0,false,2)>2</div></td></tr>";
	HTMLgametable = HTMLgametable + "<tr><td colspan='4'><h3>מה חושבים החבר'ה?</h3></td></tr>";
	for(i=0;i<maxCol;i++){		
		HTMLgametable = HTMLgametable + "<tr>";
		for (j=0;j<4;j++){
			if(gameProfile[j].length>i){
				HTMLgametable = HTMLgametable + "<td align='center'>" + gameProfile[j][i] + "</td>";
			}
			else{
				HTMLgametable = HTMLgametable + "<td></td>";
			}	
		}
		HTMLgametable = HTMLgametable + "</tr>";
	}
	return HTMLgametable;
}

// a help function in building the disagreement table in CreateSingleGameTable.
function FindMaxCol(gameProfile){
	var max = 0;
	var temp = 0;
	//var tempArr = null;
	for(i=0;i<gameProfile.length;i++){
		temp = gameProfile[i].length;
		max = (temp > max ? temp : max);
	}
	return max;
}

function isDone(game){
	var sub_count = 0;
	var row_count = 0;
	for ( row = 0; row < 16; row++ )
	{   sub_count = 0;
	for ( col = 0; col < 3; col++ ){
		if ( game[ row ][ col ] ) 
			sub_count=sub_count+1;
	}
	if (sub_count>0)
		row_count=row_count+1;

	}
	row_count=16-row_count;
	return row_count;

}

/* this function returns an array where:
		results[0..15]=the number of marks in each row
		results[16]= total number of colums
		results[17]= total number of singles
		results[18]= total number of doubles
		results[19] total number of triplets */
function getCols(game){
	var doubles=0;
	var triplets=0;
	var singles=0;
	var totalCols=0;
	var results=new Array();
	for (i=0;i<16;i++){
		rowmarks=calcMarksInRow(game,i);
		results[i]=rowmarks;
		if (rowmarks==1) singles++;
		if (rowmarks==2) doubles++;
		if (rowmarks==3) triplets++;
	}
	if (singles+doubles+triplets!=0)
		totalCols= Math.pow(2,doubles)*Math.pow(3,triplets);
	results[16]=totalCols;
	results[17]=singles;
	results[18]=doubles;
	results[19]=triplets;

	return results;	

}

//this function calculated how many marks are in a single row
function calcMarksInRow(game,row){
	if ((game[row][0]) && (game[row][1]) && (game[row][2])) return 3;
	if ((!game[row][0]) && (!game[row][1]) && (!game[row][2])) return 0;
	if ((!game[row][0]) && (game[row][1]) && (game[row][2])) return 2;
	if ((game[row][0]) && (!game[row][1]) && (game[row][2])) return 2;
	if ((game[row][0]) && (game[row][1]) && (!game[row][2])) return 2;
	return 1;
}

//this function gets the current number of doubles and triplets as parameters and returns an error code accordingly.
function legalFillout(doubles,triplets){
	if (triplets>5) return 0;
	if ((triplets==5) && (doubles>0)) return 0;
	if ((triplets==4) && (doubles>2)) return 1;
	if ((triplets==3) && (doubles>4)) return 2;
	if ((triplets==2) && (doubles>5)) return 3;
	if ((triplets==1) && (doubles>7)) return 4;
	if ((triplets==0) && (doubles>8)) return 5;
	return 10;
}

//this function alerts the user if his request is ilegal, based on the error code it got as a parameter.
function alertFillout(number){
  
	if (number==0) 	jAlert('בטור עם 5 משולשים לא ניתן לסמן כפולים', 'סימון לא חוקי');	
	if (number==1)	jAlert('בטור עם 4 משולשים ניתן לסמן לכל היותר 2 כפולים', 'סימון לא חוקי'); 	
	if (number==2) 	jAlert('בטור עם 3 משולשים ניתן לסמן לכל היותר 4 כפולים', 'סימון לא חוקי');	
	if (number==3) 	jAlert('בטור עם 2 משולשים ניתן לסמן לכל היותר 5 כפולים', 'סימון לא חוקי');	
	if (number==4) 	jAlert('בטור עם משולש יחיד ניתן לסמן לכל היותר 7 כפולים', 'סימון לא חוקי');	
	if (number==5) 	jAlert('בטור ללא משולשים ניתן לסמן לכל היותר 8 כפולים', 'סימון לא חוקי');
		
}

/***********************************NEW GENERIC FUNCTION**********************************/
/* A generic function that constructs default arrays. 					*/ 
/* s1 and s2 denote the length and the width of the array, respectively;*/
/* init_value denoted the initialization values.         				*/
function constructArray(s1,s2,init_value){
	var my_array=new Array(s1);
	for ( i = 0; i < s1; i++ ){
		if (s2>1){
			my_array[i]=new Array (s2);
			for ( j = 0; j < s2; j++ )
				my_array[i][j]=init_value;
		}
		else
			my_array[i]=init_value;
	}
	return my_array;
}
/* The initial state of a game. */          
function defaultGame(){
	return constructArray(16,3,false);
}

	function defaultOldFormList(){
		var array=new Array();
		return array;
	}
	
function defaultCorrectResultsDisplay(){
	return constructArray(16,3,0);
}
function defaultAccount(){
	return constructArray(16,3,'');
}
function defaultCorrectResults(){
	return constructArray(16,1,0); 
}
function defaultProfile(){
	return constructArray(16,3,0); 
}
function defaultAgreement(){
	return constructArray(16,1,0);
}
/* A generic function that gets some non-string object from the state*/
/* my_key denotes the key of the object in the state*/
/* my_d denotes the default function that generates the default object*/
function getSomething (my_key,my_d){
	if ( wave.getState() ){
		var my_val = eval( "(" + wave.getState().get( my_key) + ")" );
		return my_val ? my_val : my_d;
	}
	else
		return my_d;
}
/* Get the state for the current game. */
function gameState(){
	return getSomething ("game",defaultGame());
}

	function getOldFormsListFromState(){
		return getSomething("oldFormsList",defaultOldFormList());
	}

/* Get the state of the current results. */
function correctResultsDisplayState(){	
	return getSomething ( "correctResultsDisplay",defaultCorrectResultsDisplay());
}
/* Get the state of the last week results. */
function lw_correctResultsDisplayState(){
	return getSomething ("lw_correctResultsDisplay",defaultCorrectResultsDisplay());
}
/* Get the state for the last week game. */
function last_week_gameState(){	
	return getSomething ("last_week_game",defaultGame());
}
/* Get the account for the current game. */
function accountState(){	
	return getSomething ("account",defaultAccount());
}
/* Get the account for the current profile of the parId participant. */
function profileState(parId){
	return getSomething (parId,defaultProfile());
}
/* Get the state for the current agreement. */
function agreementState(){
	return getSomething ("agreement",defaultAgreement());
}

/* Get the current games column from the state */
function GamesStrState(){
	if ( wave.getState() ){
		var GamesStr = wave.getState().get( "GamesStr" );
		return GamesStr ? GamesStr : "";
	}
	else{
		return "";
	}
}

/* 	Get the recommendations from the state as an array*/
/*	(type==0) -> textual recommendations, (type==1) -> final recommendations */
function Recommendations(type){
	if ( wave.getState() ){
		var RecStr = wave.getState().get( "RecStr" );
		if(!RecStr){
			return [];
		}
		else{
			var TypesArray = RecStr.split("#");
			var RecArray = TypesArray[type].split("$");
			return RecArray;
		}
	}
	else
	{
		return [];
	}
}

//returns an array of the stat links
function StatURLsState(){
	if ( wave.getState() ){
		var StatLinksStr = wave.getState().get( "StatLinksStr" );
		if(!StatLinksStr){
			return [];
		}
		else{
			var StatArray = StatLinksStr.split("$");
			return StatArray;
		}
	}
}

/* Set the state of a cell in the display. */
function setCell( row, col, on )
{
	document.getElementById( "cell" + row + col ).className = on ? "cellOn" : "cellOff";
}

/* Do Something for each cell in the game. */
function forEachCell( f )
{
	for ( row = 0; row < 16; row++ )
	{
		for ( col = 0; col < 3; col++ )
		{
			f( row, col );
		}
	}
}

/* Refresh the grid based on the current game state. */
function refreshGrid( gameState )
{
	if(parseInt(wave.getState().get("ResultsReq"))){
		RefreshResultsDisplay();
		//display the results guide
		document.getElementById("main_symbols_table").setAttribute("class", "symbols_table");
	}
	else{		   
		forEachCell( function( row, col ) { setCell( row, col, gameState[ row ][ col ] ) } );
		//while playing no need for a results guide
		document.getElementById("main_symbols_table").setAttribute("class", "symbols_table_invisible");
	}
}

/* Get the count of cells switched on. */
function onCount( gameState )
{
	var count = 0;

	forEachCell( function( row, col ) { if ( gameState[ row ][ col ] ) count++; } );

	return count;
}
//This function resets the game board and all of this weeks user data (talkbacks, personal form etc.)
function doReset(answer){
	if (answer !=0){ 
		var par=wave.getParticipants();
		var delta = {};
		//clear the agreement Array
		delta["agreement"] = wave.util.printJson(defaultAgreement());
		//clear the personal profiles ,talkback counters and hesitation countes
		var newProfile = wave.util.printJson(defaultProfile());
		for (i = 0; i < par.length;i++){
			delta[par[i].getId()] = newProfile;
			delta[par[i].getId() + "TBcounter"]=0;
			delta[par[i].getId() + "HC"]=0;
			delta[par[i].getId() + "HChelper"]=0;
		}
		//clear the cost
		delta["cost"]="0";
		//clear the form's account
		delta["account"]=wave.util.printJson(defaultAccount());
		//clear the actuall board
		delta["game"]=wave.util.printJson(defaultGame());
		//clear talkbacks
		delta["TalkBackString"]="#@&del#@&del#@&del#@&del#@&del#@&del#@&del#@&del#@&del#@&del#@&del#@&del#@&del#@&del#@&del"
		//submit the changes
		wave.getState().submitDelta(delta);
	}
}

//this function get an array and its length and reverses it
function reverseArray(results,n){
	var temp=0;
	for (i=0;i<Math.floor(n/2);i++){
		temp=results[i];
		results[i]=results[n-i-1];
		results[n-i-1]=temp;
	}
	return results;
}

function refreshCost(){
	var price=getCost().toFixed(2);
	document.getElementById('cost_number').innerHTML = price;
}

/* enter the start day and end day and the function returns "true" if the current time is between start and end*/
function IsRightTime(start,end){
	var now = currentTime();
	if( now > start && now < end){
		return true;
	}
	else{
		return false;
	}
}

/*dates are stored as epoch time in the state. this getter will create a date object of a certain
   		  epoch time stored in "lable". if the label does not exist --> return a date 1/1/1970 00:00*/
function getDateFromState(label){
	d = parseInt(wave.getState().get(label));
	d = new Date(d);
	return d;
}

function NewForm(flag){
	curTime = currentTime();
	if (flag==1) verifyWaveID(); // <Gili> added to support a case where we don't have a wave ID for some reason
	//alert(curTime.getDay());
	// while games are on - you cannot NewForm(). only reset the board.
	if(	(curTime.getDay() ==0) ||
			((curTime.getDay() ==1) && (curTime.getHours()< 16)) ||
			((curTime.getDay() ==6) && (curTime.getHours()> 11))) { 
			doReset(1);
		//alert("just a board reset");
	}
	else{ // an actuall request for a new form on a legal day.
		var dateFromState = wave.getState().get("cellClickUpperLimit"); //need to use the function getDateFromState() here
		var currentGameDate = setToSpecificTime(6,12,0).getTime();
		if (currentGameDate!=parseInt(dateFromState)){//if this is an actuall time change related NewForm
			var arrayOfDates= getOldFormsListFromState();
			var gamesString=GamesStrState();  //this object will hold the games data.
			var formFillout= wave.util.printJson(gameState());; //this object will hold what we filled in the form.
			var crrectResults=wave.util.printJson(correctResultsDisplayState());//this object will hold the results
			var cost=getCost();
			var prize=wave.getState().get("prize");
			var numberOfCorrectGuesses=wave.getState().get("numberOfCorrectGuesses");
			var idiotID=wave.getState().get("idiotID");
			var hotID=wave.getState().get("hotID");
			
			RefreshData(0);//get the current games
			RefreshData(4);
			cellClickUpperLimit = setToSpecificTime(6,12,0); // cellclicks allowed only before saturday, 12AM.
			cellClickLowerLimit = new Date(cellClickUpperLimit.getTime() - 5*86400000 -5*3600000);// and after monday , 7AM.
			resultsLowerLimit = setToSpecificTime(1,16,0);//results are in only on moday 4PM.
			resultsUpperLimit = new Date(resultsLowerLimit.getTime() + 6*86400000);//results are available for 6 days only.
			recommendationsUpperLimit = setToSpecificTime(0,18,30);// new recommendations are available between 
			recommendationsLowerLimit = new Date(recommendationsUpperLimit.getTime()-4*86400000); // wednesday 6:30PM and sunday 6:30PM.
			wave.getState().submitDelta({	"cellClickUpperLimit" : cellClickUpperLimit.getTime(),
				"cellClickLowerLimit" : cellClickLowerLimit.getTime(),
				"resultsUpperLimit"   : resultsUpperLimit.getTime(),
				"resultsLowerLimit"   : resultsLowerLimit.getTime(),
				"recommendationsUpperLimit" : recommendationsUpperLimit.getTime(),
				"recommendationsLowerLimit" : recommendationsLowerLimit.getTime(),
				"IsPlaying" : "1",
				"ResultsReq" : "0",
				"RecommendationsReq" : "0",
				"lastUpdatedTB" : "0"
			});
			if (flag==1){
				lastWeek(); //transfer the old data to lw labels in the state
				insertToOldFormList(dateFromState,arrayOfDates);			//<Gili>	puts the cellclickUpperLimit in the list of dates
				post(gamesString,formFillout,crrectResults,cost,prize,numberOfCorrectGuesses,idiotID,hotID);	//<Gili>	stores the form data in app engine
			}
			doReset(1);
		}else{//just a reset
		
		jConfirm('האם ברצונך לאפס את הטופס? <br> כל הסימונים,הטוקבקים והטפסים האישיים ימחקו', 'טופס חדש', function(r) {
		if (r==true) {
      doReset(1);
      jAlert('הטופס אופס' , 'טופס חדש');
    }
    else {
      jAlert('פעולה בוטלה' , 'טופס חדש');
    }});
		}
	}
}

//this function updates the list of past forms with a new date (== the date of the previous week).
function insertToOldFormList(dateFromState,arrayOfDates){
		arrayOfDates.push(dateFromState);
		wave.getState().submitDelta( { "oldFormsList"  : wave.util.printJson( arrayOfDates )});
		}

function currentTime(){
	var D = new Date();
	return D;
}

//defines a date for wanted specific time in range of a week
function setToSpecificTime(day,hour,minute){
	var now = currentTime();
	var today = now.getDay();
	var daysDelta = ((day - today) < 0 ? (day - today + 7) : (day - today));
	var specificDate = new Date(now.getTime() + (86400000*daysDelta));
	specificDate.setHours(hour);
	specificDate.setMinutes(minute);
	specificDate.setSeconds(0,0);
	//make sure specific date is in the future
	var finalDate = ((specificDate < now) ? (new Date(specificDate.getTime() + (86400000*7))) : specificDate );
	return finalDate;
}

function RecommendationsToState(){
	if(IsRightTime(getDateFromState("recommendationsLowerLimit"),getDateFromState("recommendationsUpperLimit"))){
		RefreshData(2);
		wave.getState().submitDelta({ "RecommendationsReq" : "1"}); //for the display of recommendations
	}
}

function ResultsToState(){
	if(IsRightTime(getDateFromState("resultsLowerLimit"),getDateFromState("resultsUpperLimit")) && (!parseInt(wave.getState().get("ResultsReq")))){
		RefreshData(1);
		//wave.getState().submitDelta({ "ResultsReq" : "1"}); //for display of results
	}
}

//watch the state for debuging
function debug(){ 
	var s = wave.getState().toString();
	alert(s);
}


/* 	this function updates the games,days and leagues.
		the GamesStr (taken from the state is) is a string containing all the data. 
		the string is saparated by 2 types of delimiters: 
		# - for spliting games from days,days from leagues.
		$ - for spilting within types of information(i.e. game1 from game2,day1 from day2 and so on).	*/		
function RefreshGames(){
	var GamesStr = GamesStrState();
	var games_arr;
	if(GamesStr && GamesStr!=""){
		var FieldsArray = GamesStr.split("#");
		FieldsArray = reverseArray(FieldsArray,3);
		for(j=3;j<6;j++){
			tempFieldArray = FieldsArray[j-3].split("$");
			for (i=0;i<16;i++){
				document.getElementById( "cell" + i + j ).innerHTML = "<div style='overflow: hidden; height: 16px;'>"+tempFieldArray[15-i]+"</div>";
			}
		}
	}
}

/*********** talkback Part **********************************/
	//trimming Strings
	String.prototype.trim = function () {
		return this.replace(/^\s*/, "").replace(/\s*$/, "");
	}
	
	function submitTalkBack(gameNum){
		var TalkBackArray = getTalkBackArray();
		var newText = document.getElementById('newText'+gameNum).value;
		
		if(newText.trim() != ""){
			delta = {};
			TalkBackArray[gameNum] = TalkBackArray[gameNum] +	
									"<div style='width:90%;'><p class='tb_us_name'>" +
									wave.getViewer().getDisplayName() + 
									": <p>" + newText +"</div>";
			str = TalkBackArray[0];
			for(i=1;i<16;i++){
				str = str + "#@&del" + TalkBackArray[i];
			}
			//updating the talkback counter
			var parId = wave.getViewer().getId();
			var TBcounter = getTBcounter(parId);
			TBcounter=TBcounter+1;			
			//updating the state	
			delta[parId + "TBcounter"]=TBcounter;
			delta["TalkBackString"]=str;
			delta["lastUpdatedTB"]=gameNum;
			wave.getState().submitDelta(delta);
			var newText = document.getElementById('newText'+gameNum).value="";//clearing the text area.
		}
	}
	
	// getter for the counter of parId's current TBcounter
	function getTBcounter(parId){
		return getSomething(parId+'TBcounter',0);
	}

	function refreshTalkBacks(){
		var lastUpdatedTB = wave.getState().get("lastUpdatedTB");
		var TalkBackArray = getTalkBackArray();
		for(i=0 ; i<16 ; i++){
			document.getElementById('oldText' + i).innerHTML = "<div class='tb_title'> תגובות על המשחק: <b>" + document.getElementById("cell"+i+"3").innerHTML + "</b></div>" + TalkBackArray[i];
		}
		//resizing of the colorbox when needed
		if(document.getElementById('oldText' +lastUpdatedTB).offsetHeight < 400){
				$.fn.colorbox.resize();
		}	
	}
	
	
	function getTalkBackArray(){
		if ( wave.getState() ){
			var TalkBackArray = wave.getState().get("TalkBackString");//eval( "(" + wave.getState().get("TalkBackArray") + ")" );
			if(TalkBackArray){
				TalkBackArray = TalkBackArray.split("#@&del");
				return TalkBackArray;
			}
			else{
				return new Array("","","","","","","","","","","","","","","","");
			}
		}
		else{
			return new Array("","","","","","","","","","","","","","","","");
		}
	}
	
	function defaultTalkBackString(){
		return "#@&del#@&del#@&del#@&del#@&del#@&del#@&del#@&del#@&del#@&del#@&del#@&del#@&del#@&del#@&del";
	}
	/************************************************************************/
		function verifyWaveID(){
		var waveID=parseInt(wave.getState().get( "waveID","0" ));
		if (!(waveID>0)) getWaveIDfromDB();
	}
	